package com.sfx.多线程代码题;

import java.util.ArrayList;
import java.util.List;

class Solution {
    private List<String> res = new ArrayList<>();
    private StringBuilder st = new StringBuilder();

    private void backTracking(int n, int left, int right) {
        if (left > n || right > n) return;
        if (left == n && left == right) {
            res.add(st.toString());
            return;
        }
        if (left < n) {
            st.append("(");
            backTracking(n, left + 1, right);
            st.deleteCharAt(st.length() - 1);
        }
        if (left > right) {
            // left > right;
            st.append(")");
            backTracking(n, left, right + 1);
            st.deleteCharAt(st.length() - 1);
        }
    }

    public List<String> generateParenthesis(int n) {
        backTracking(n, 0, 0);
        return res;
    }
}